import { ref, computed, onMounted } from 'vue';
import { defineStore } from 'pinia'
import { useUserStore } from '@/stores/userStore'
import { ElMessage } from 'element-plus';
export const useCouponStore = defineStore('coupon', () => {
    //从localStorage中获取优惠卷
    const coupon = JSON.parse(localStorage.getItem('coupons')) || [];
    const selectedCoupon = ref(null); // 绑定选中的优惠券ID
    const selectedDiscount = ref(0); // 绑定的折扣值
    //优惠卷改变时
    const updateDiscount = (value) => {
        console.log(selectedCoupon.value);
        console.log(coupon);
        const selectedOption = options.find(option => option.value === value)

        selectedDiscount.value = selectedOption ? selectedOption.discount : 0
    }
    // 根据选中的优惠券 ID 删除对应的优惠券
    const deleteCoupon = (id) => {
        const couponID = selectedCoupon.value
        const updatedCoupon = coupon.filter(item => item.id !== couponID)
        //弹出数组
        localStorage.setItem('coupons',JSON.stringify(updatedCoupon))
        // 清空选择的优惠券和折扣
        selectedCoupon.value = null
        selectedDiscount.value = 0
    }
    //优惠券选项
    const options = [
        {
            label: '不使用优惠券',
            value: 0,
            discount: 0
        },
        //遍历优惠券数组，将优惠券信息添加到options数组中
        ...coupon.map(item => ({
            label: item.title + '-' + '折扣' + item.discount + '元',
            value: item.id,
            discount: item.discount
        })),
    ]
    //设置新用户优惠券有效时间
    const setNewUserCouponValidity = () => {
        const date = new Date();
        date.setMonth(date.getMonth() + 3); // 领取后3个月有效
        return date.toISOString().split('T')[0]; // 格式化日期
    }
    //设置回馈老客户优惠券有效时间
    const setFeedbackCouponValidity = () => {
        const date = new Date();
        date.setMonth(date.getMonth() + 1); // 领取后2个月有效
        return date.toISOString().split('T')[0]; // 格式化日期
    }
    //设置新年优惠券有效时间，只在大年初一到大年初八有效
    const setNewYearCouponValidity = () => {
        const year = new Date().getFullYear();
        const yearStart = new Date(year, 1, 10);
        const yearEnd = new Date(year, 1, 17);
        if (new Date() >= yearStart && new Date() <= yearEnd) {
            return new Date(year, 1, 10).toISOString().split('T')[0]; // 格式化日期
        } else {
            return new Date(year - 1, 1, 10).toISOString().split('T')[0]; // 格式化日期
        }
    }
    //周末优惠券有效时间
    const setWeekendCouponValidity = () => {
        const date = new Date();
        const dayOfWeek = date.getDay(); // 获取当前日期是周几，0 是周日，1 是周一，...，6 是周六
        // 判断当前日期是否为周日或周六
        if (dayOfWeek === 0 || dayOfWeek === 6) {
            // 周日或周六，领取后1天有效
            const date = new Date();
            date.setDate(date.getDate() + 1);
            return date.toISOString().split('T')[0]; // 格式化日期
        } else {
            //不在有效日期范围内，不发放优惠券
            date.setDate(date.getDate() - 7);
            return date.toISOString().split('T')[0]; // 格式化日期
        }
    }
    //节日优惠券有效时间
    const setHolidayCouponValidity = () => {
        const date = new Date();
        const year = date.getFullYear();
        const month = date.getMonth() + 1;
        const day = date.getDate();
        const holidays = [
            new Date(year, 0, 1), // 元旦
            new Date(year, 1, 15), // 中秋节
            new Date(year, 2, 8), // 妇女节
            new Date(year, 3, 1), // 植树节
            new Date(year, 4, 5), // 清明节
            new Date(year, 5, 1), // 劳动节
            new Date(year, 6, 1), // 端午节
            new Date(year, 7, 1), // 中秋节
            new Date(year, 8, 15), // 中秋节
            new Date(year, 9, 8), // 教师节
            new Date(year, 11, 1), // 万圣节
        ];
        for (let i = 0; i < holidays.length; i++) {
            const holiday = holidays[i];
            if (month === holiday.getMonth() + 1 && day === holiday.getDate()) {
                // 找到节日，领取后1天有效
                const date = new Date();
                date.setDate(date.getDate() + 1);
                return date.toISOString().split('T')[0]; // 格式化日期
            } else {
                // 未找到节日，时间为前一天
                const date = new Date();
                date.setDate(date.getDate() - 1);
                return date.toISOString().split('T')[0]; // 格式化日期
            }
        }
    }
    //限时抢购券有效时间
    const setLimitTimeCouponValidity = () => {
        const startDate = new Date(); // 当前时间
        const endDate = new Date(startDate.getTime() + 3600 * 1000 * 24 * 1); // 有效期1天
        return endDate.toISOString().split('T')[0]; // 格式化日期
    }
    // 优惠券列表
    const coupons = ref([
        { id: 1, title: '新用户专享', discount: 50, validity: setNewUserCouponValidity() },
        { id: 2, title: '满300减100', discount: 100, validity: '有效期至 2023-11-30' },
        { id: 3, title: '全场通用券', discount: 20, validity: '有效期至 2025-06-15' },
        { id: 4, title: '大额优惠券', discount: 200, validity: '有效期至 2023-12-01' },
        { id: 5, title: '节日特惠', discount: 30, validity: setHolidayCouponValidity() },
        { id: 6, title: '回馈老客户', discount: 70, validity: setFeedbackCouponValidity() },
        { id: 7, title: '精选商品专享', discount: 150, validity: '有效期至 2023-12-31' },
        { id: 8, title: '限时抢购券', discount: 90, validity: setLimitTimeCouponValidity() },
        { id: 9, title: '周末特惠', discount: 40, validity: setWeekendCouponValidity() },
        { id: 10, title: '新春佳节券', discount: 60, validity: setNewYearCouponValidity() },
    ]);
    //1.从pinia中获取token
    const userStore = useUserStore()
    //2.在请求头中添加token
    const token = userStore.userInfo.token
    //实例化couponStore
    const couponStore = useCouponStore()
    // 2. 响应式数据保存已领取的优惠券列表
    const receivedCoupons = ref([]);
    // 初始化已领取的优惠券
    const loadReceivedCoupons = () => {
        receivedCoupons.value = JSON.parse(localStorage.getItem('coupons')) || [];
    };
    //按钮逻辑
    const claimCoupon = (id) => {
        const coupon = coupons.value.find(item => item.id === id); // 根据优惠券 ID 找到优惠券对象
        if (token) {
            //判断是否已领取
            if (hasReceivedCoupon(id)) {
                ElMessage.warning('您已领取过该优惠券！')
                return
            }
            //判断优惠券是否有效
            if (isCouponValid(coupon)) {
                ElMessage.warning('该优惠券已过期，无法领取！');
                return;
            }
            ElMessage.success('领取成功！')
            receivedCoupons.value.push(couponStore.coupons[id - 1]); // 将当前优惠券 ID 加入数组
            localStorage.setItem('coupons', JSON.stringify(receivedCoupons.value)); // 更新 localStorage
        } else {
            ElMessage.warning('请先登录！')
        }
    };
    //计算属性 判断是否领取优惠券
    const hasReceivedCoupon = (id) => {
        return receivedCoupons.value.some(coupon => coupon && coupon.id === id); // 判断数组中是否有对象的id等于当前id
    }
    //判断优惠卷是否有效
    const isCouponValid = (coupon) => {
        const now = new Date();
        const validDate = new Date(coupon.validity);
        return validDate < now; // true 表示已过期
    }
    // 组件挂载后初始化已领取的优惠券
    onMounted(() => {
        loadReceivedCoupons()
    })
    return {
        coupons,
        claimCoupon,
        hasReceivedCoupon,
        isCouponValid,
        updateDiscount,//checkout页面优惠卷改变时
        selectedCoupon,// 绑定选中的优惠券ID
        selectedDiscount,// 绑定的折扣值
        options,// 优惠券选项
        deleteCoupon
    }
}, {
    persist: true
})
